/**
 * 
 * @author  phoenics@126.com
 * @version v.0.1
 * @date  2018年3月22日 上午11:05:07 
 * 
 */
package phoenics.upservice.restcontroller;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import phoenics.common.BaseData.RestResp;
import phoenics.upservice.OSSClientConstants;
import phoenics.upservice.auth.JwtAuthentication;
import phoenics.upservice.dto.BuyDto;
import phoenics.upservice.dto.ListPage;
import phoenics.upservice.dto.ListTerm;
import phoenics.upservice.dto.Order;
import phoenics.upservice.dto.ProjectDTO;
import phoenics.upservice.dto.ProjectPicDTO;
import phoenics.upservice.dto.UserProjectDto;
import phoenics.upservice.entity.Project;
import phoenics.upservice.entity.User;
import phoenics.upservice.entity.UserProject;
import phoenics.upservice.entity.UserProjectStatus;
import phoenics.upservice.repository.ProjectRepo;
import phoenics.upservice.repository.UserProjectRepository;
import phoenics.upservice.service.UserService;
import phoenics.upservice.service.UtilSerice;

/**
 *
 */
@Api(value = "与订单相关API")
@RestController  
@RequestMapping("/order")  
public class OrderService {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OrderService.class);
	 private SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd");
		@Autowired
		ProjectRepo projectRepo;
		@Autowired
		UserProjectRepository userProjectRepository;
		@Autowired
		UserService userService;
		@Autowired
		UtilSerice utilSerice;
		
		@ApiOperation(value = "工程订单信息列表list", notes = "")  
		@GetMapping  (value = "/mylist")
		public RestResp projectOrders(
				) {
			JwtAuthentication j=(JwtAuthentication)SecurityContextHolder.getContext().getAuthentication();
			if(j==null) {
				return RestResp.fail("未登录");
			}
			User userE=(User)j.getPrincipal();
			//logger.info("ddddddddddddddddd");
			List<UserProject> ups=projectRepo.findOrders(userE.getId());
			//logger.info(userE.getId()+""+ups.size());
			List<ListPage> content= ups.stream().map(u->utilSerice.ListPageMapper(u.getProject())
			).collect(Collectors.toList());
			//logger.info("===========================================");
			//Page<ListPage> pages=new PageImpl<>(content,pageable,ups.getTotalElements());
			
			return RestResp.success(content);
		}
		@ApiOperation(value = "自己工程信息列表list", notes = "")  
		@GetMapping  (value = "/mylist2")
		public RestResp projectOrders2(
				) {
			User userE=userService.takePrincipal();
			//logger.info("ddddddddddddddddd");
			//List<UserProject> ups=projectRepo.findOrders(userE.getId());
			//logger.info(userE.getId()+""+ups.size());.
			List<Project> ups=projectRepo.findByUserId(userE.getId());
			List<ListPage> content= ups.stream().map(u->utilSerice.ListPageMapper(u)
			).collect(Collectors.toList());
			//logger.info("===========================================");
			//Page<ListPage> pages=new PageImpl<>(content,pageable,ups.getTotalElements());
			
			return RestResp.success(content);
		}
		
	@ApiOperation(value = "工程订单信息列表page", notes = "")  
	@GetMapping  (value = "/list")
	public RestResp projectOrders(
			@RequestParam(value = "up", defaultValue = "0") Integer up,
			@RequestParam(value = "page", defaultValue = "0") Integer page,
			@RequestParam(value = "size", defaultValue = "10") Integer size
			) {
		Sort sort = new Sort(Direction.DESC, "id");
		Pageable pageable = new PageRequest(page, size, sort);
		if(up!=0) {
			pageable = new PageRequest(0, Integer.MAX_VALUE, sort);
		}
		JwtAuthentication j=(JwtAuthentication)SecurityContextHolder.getContext().getAuthentication();
		if(j==null) {
			return RestResp.fail("未登录");
		}
		User userE=(User)j.getPrincipal();
		Page<UserProject> ups=projectRepo.findOrders(userE.getId(),pageable);
		List<ListPage> content= ups.getContent().stream().map(u->utilSerice.ListPageMapper(u.getProject())
		).collect(Collectors.toList());
		Page<ListPage> pages=new PageImpl<>(content,pageable,ups.getTotalElements());
		return RestResp.success(pages);
	}
	@ApiOperation(value = "工程订单详细信息", notes = "")  
	@GetMapping  (value = "/list/{id}")
	public RestResp projectOrderDetails(@PathVariable("id") Long id) {
		JwtAuthentication j=(JwtAuthentication)SecurityContextHolder.getContext().getAuthentication();
		if(j==null) {
			return RestResp.fail("未登录");
		}
		User userE=(User)j.getPrincipal();
		 UserProject up=projectRepo.findOneOrder(userE.getId(),id);
		 //UserProject up = opUp.get();
		if(up==null) {
			return RestResp.fail("没要这条信息");
		}
		Project project=up.getProject();
		ProjectDTO projectDTO=pDetails(project);
		projectDTO.setProjectAddress("***");
		projectDTO.setProjectDuties1Tel("***");
		projectDTO.setProjectDuties2Tel("***");
		projectDTO.setProjectDuties3Tel("***");
		UserProjectDto dto=new UserProjectDto();
		dto.setPrice(up.getPrice());
		dto.setOrdernumber(up.getOrdernumber());
		//dto.setPrice(up.getPrice());
		//dto.setProjectId(up.getProject().getId());
		dto.setProjectDto(projectDTO);
		return RestResp.success(dto);
	}
	private ProjectDTO pDetails(Project project) {
		ProjectDTO projectDTO=new ProjectDTO();
		//Project project=projectRepo.findOne(id);
		BeanUtils.copyProperties(project,projectDTO);
		projectDTO.setOpenDate(myFmt.format(project.getOpenDate()));
		List<ProjectPicDTO> pdto=Optional.ofNullable( project.getProjectPics()).orElseGet(Collections::emptyList)
				.stream().map(p->{
			ProjectPicDTO dto=new ProjectPicDTO();
			dto.setDetail(p.getDetail());
			dto.setPicUrl(OSSClientConstants.HTTPPATH+p.getPicUrl());
			return dto;
		}).collect(Collectors.toList());
		projectDTO.setProjectPics(pdto);
		return projectDTO;
	}

	private UserProject addOrder(Project p,Order order,User userE) {
		UserProject up=new UserProject();
		up.setProject(p);
		up.setUser(userE);
		up.setOrdernumber(order.getOrdernumber());
		up.setPrice(order.getPrice());
		return up;
	}
	
	
	

	@ApiOperation(value = "增加订单", notes = "")  
	@PostMapping  (value = "/add")
	public RestResp projectOrderAdd(@RequestBody Order order) {
		JwtAuthentication j=(JwtAuthentication)SecurityContextHolder.getContext().getAuthentication();
		if(j==null) {
			return RestResp.fail("未登录");
		}
		User userE=(User)j.getPrincipal();
		//UserProject up=projectRepo.findOneOrder(userE.getId(),order.getProjectId());
		UserProject up=projectRepo.findOneOrder(userE.getId(),order.getProjectId());
		if(up!=null) {
			return RestResp.fail("400404");
		}
		return projectRepo.findById(order.getProjectId()).map(p->addOrder(p,order,userE))
				.map(upp->userProjectRepository.save(upp))
				.map(u->{
					BuyDto by=new BuyDto();
					by.setId(u.getId());
					by.setPrice(u.getPrice());
					return by;
				})
				.map(i->RestResp.success(i))
				.orElse(RestResp.fail("数据错误"));
		
	}
	@ApiOperation(value = "取消订单", notes = "")  
	@DeleteMapping  (value = "/list/{id}/del")
	public RestResp projectOrderAdd(@PathVariable("id") Long id) {
		JwtAuthentication j=(JwtAuthentication)SecurityContextHolder.getContext().getAuthentication();
		if(j==null) {
			return RestResp.fail("未登录");
		}
		User userE=(User)j.getPrincipal();
		//UserProject up=projectRepo.findOneOrder(userE.getId(),id);
		userProjectRepository.findOneOrder(userE.getId(),id).ifPresent(u->userProjectRepository.deleteById(u.getId()));
		return RestResp.success(1);
		
	}
	
	
	
	
	
	
	
	
}
